package export

import (
	"GOPAAS/internal/utils"
	"GOPAAS/tools/csv"
	"GOPAAS/tools/excel"
	myzip "GOPAAS/tools/zip"
	"os"
	"path/filepath"
	"sync"
	"time"
)

const EXPORT_LIMIT = 5000

// export 导出数据
func Export(title []string, result [][]string, file_type string) (dowload_path string, err error) {

	year := time.Now().Format("2006")
	month := time.Now().Format("01")
	upload_path := "upload/" + year + month
	if _, path_err := os.Stat(upload_path); os.IsNotExist(path_err) {
		// 必须分成两步
		// 先创建文件夹
		os.Mkdir(upload_path, 0777)
		// 再修改权限
		os.Chmod(upload_path, 0777)
	}
	var file_path_arr []string
	var data [][]string
	data = append(data, title)
	var file_path string
	var wwg sync.WaitGroup
	for k, v := range result {
		data = append(data, v)
		if len(data) > EXPORT_LIMIT {
			wwg.Add(1)
			go func(data1 [][]string) {
				file_name := utils.GetUuid(32, k) + ".xlsx"
				file_path = upload_path + "/" + file_name
				if file_type == "xlsx" {
					err = excel.CreateExcelFile("sheet1", file_path, data1)
				} else {
					err = csv.ExportCsv(upload_path+"/"+file_name, data1)
				}
				file_path_arr = append(file_path_arr, file_path)
				wwg.Done()
			}(data)
			data = [][]string{title}
		}
	}
	file_name := utils.GetUuid(32, 1) + ".xlsx"
	file_path = upload_path + "/" + file_name
	if file_type == "xlsx" {
		err = excel.CreateExcelFile("sheet1", file_path, data)
	} else {
		err = csv.ExportCsv(upload_path+"/"+file_name, data)
	}
	file_path_arr = append(file_path_arr, file_path)
	wwg.Wait()
	if len(file_path_arr) == 1 {
		dowload_path = file_path_arr[0]
	} else {
		tar_dir := upload_path + "/" + "tmp/"
		os.Mkdir(tar_dir, 0777)
		os.Chmod(tar_dir, 0777)
		for _, f_path := range file_path_arr {
			filename := filepath.Base(f_path)
			os.Rename(f_path, tar_dir+filename)
		}
		//打包的文件名
		fileTarget := upload_path + "/" + utils.GetUuid(32, 1) + ".zip"
		// 需要打包的文件路径
		err = myzip.Zip(fileTarget, tar_dir)
		if err != nil {
			return
		}
		dowload_path = fileTarget
	}
	return
}
